﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Application.Impl
{
    using EC.Application.Interface;

    using EC.Entity;
    using EC.Entity.Enum;
    using EC.Entity.Query;
    using EC.Entity.Request.DepositRecord;
    using EC.Entity.Response.BankCard;
    using EC.Entity.Response.DepositRecord;
    using EC.Entity.Response.Merchant;
    using EC.Entity.Tables;

    /// <summary>
    /// 存款记录接口实现
    /// </summary>
    public class DepositRecordServiceImpl: DepositRecordService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public DepositRecordServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public DepositRecordResponse Get(int? id)
        {
            var model = new DepositRecordResponse();
            
            //所有商户
            var merchants = _dbSession.DbConnection.Query<MerchantResponse>("SELECT * FROM merchant WHERE Status = @Status", new { Status = (int)MerchantStatus.启用 }).ToList();
            if (merchants != null && merchants.Any())
            {
                model.MerchantResponse = merchants;
            }

            //所有银行卡
            var bankCards = _dbSession.DbConnection.Query<BankCardResponse>("SELECT * FROM bankcard").ToList();
            if (bankCards != null && merchants.Any())
            {
                model.BankCardResponse = bankCards;
            }
            return model;
        }

        /// <summary>
        /// 新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveDepositRecord(SaveDepositRecordRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var depositRecordExist = _dbSession.DbConnection.Query<DepositRecordResponse>("SELECT * FROM paymentrecord WHERE MerchantId=@MerchantId And MerchantOrderNo=@MerchantOrderNo", new { MerchantId = request.MerchantId, MerchantOrderNo = request.ClientOrderNo });
                if (depositRecordExist != null && depositRecordExist.Any())
                {
                    throw new Exception("银行存款单号已存在.");
                }

                var depositRecord = new DepositRecord()
                {
                    MerchantId = request.MerchantId.Value,
                    ClientOrderNo = request.ClientOrderNo,
                    ClientBankName = request.ClientBankName,
                    ClientCardName = request.ClientCardName,
                    ClientCardNumber = request.ClientCardNumber,
                    DepositAmount = Convert.ToDecimal(request.DepositAmount),
                    DepositCardNumber = request.DepositCardNumber,
                    //DepositDate = request.DepositDate,
                    //Transtype = request.Transtype,
                    PostScript = request.PostScript,
                    CreatedBy = request.CreatedBy,
                    CreatedDate = DateTime.Now
                };

                if (request.Transtype.HasValue)
                {
                    depositRecord.Transtype = request.Transtype.Value;
                }
                if(!string.IsNullOrEmpty(request.DepositDate))
                {
                    depositRecord.DepositDate = Convert.ToDateTime(request.DepositDate);
                }
                //新增
                long resultId = _dbSession.DbConnection.Insert<DepositRecord>(depositRecord);

                if (resultId <= 0)
                {
                    throw new Exception("新增存款记录失败.");
                }

                response.Success = true;
            }
            catch(Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<DepositRecordQueryResponse> GetPager(DepositRecordQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,MerchantId,DepositOrderId,ClientOrderNo,ClientBankName,ClientCardName,ClientCardNumber,DepositAmount,DepositCardNumber,DepositDate,Transtype,PostScript,CreatedBy,CreatedDate";
            var tableName = "depositrecord";
            var orderby = "ORDER BY Id DESC";
            var where = $"where MerchantId in ({string.Join(", ", query.MerchantIds)})";

            #region 条件
            if (!string.IsNullOrEmpty(query.ClientCardName))
            {
                where += string.Format(" And ClientCardName like'%{0}%'", query.ClientCardName);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<DepositRecordQueryResponse>();

                return new PagedList<DepositRecordQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<DepositRecordQueryResponse> MatchRecord(MatchRecordQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,MerchantId,DepositOrderId,ClientOrderNo,ClientBankName,ClientCardName,ClientCardNumber,DepositAmount,DepositCardNumber,DepositDate,Transtype,PostScript,CreatedBy,CreatedDate";
            var tableName = "depositrecord";
            var orderby = "ORDER BY Id DESC";
            var where = $"where DepositOrderId IS NULL And MerchantId in ({string.Join(", ", query.MerchantIds)})";

            #region 条件
            //if (!string.IsNullOrEmpty(query.Name))
            //{
            //    where += string.Format(" And Name like'%{0}%'", query.Name);
            //}
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<DepositRecordQueryResponse>();

                return new PagedList<DepositRecordQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }
    }
}
